package com.wushi.lenovo.asia5b.app_di.goods.presenter;

import android.text.TextUtils;

import com.google.gson.JsonArray;
import com.mvp.base.model.ResultModel;
import com.mvp.common.GlobalValue;
import com.mvp.common.LocalManageUtil;
import com.mvp.utils.JsonUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.app_di.goods.mvpview.OrderPackActivityView;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_http.OrderService;
import com.wushi.lenovo.asia5b.app_model.good.DeliveriesBean;
import com.wushi.lenovo.asia5b.app_model.good.InternationalDeliveryModel;
import com.wushi.lenovo.asia5b.app_model.good.OrderPackModel;
import com.wushi.lenovo.asia5b.app_model.good.OrderPackServiceModel;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_push.PushHelper;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import timber.log.Timber;


/**
 * Created by zhangyuncai on 2020/3/6.
 */
public class OrderPackActivityPresenter extends OrderCheckCommonPresenter<OrderPackActivityView> {

    @Inject
    public OrderPackActivityPresenter(ApiService apiService, OrderService orderService) {
        super(apiService, orderService);
    }

    //收货地址
    private MapHelper lastMap;
    private MapHelper lastExtraMap;

    private JsonArray getAddServiceIds(List<OrderPackServiceModel> serviceModels) {
        JsonArray idsElement = new JsonArray();
        for (OrderPackServiceModel bean : serviceModels) {
            idsElement.add(bean.id);
        }
        Timber.d("--->>>>>>>>---join:" + idsElement);
        return idsElement;
    }

    /*
    member_id=5378&language_code=en&extra_data={"international_delivery_method":"sea","delivery_address":{"building_name":"","calling_code":"60","address":"106,Jalan Rimba Emas, Taman Bersatu","city":"Kulim","mobile":"10-2299239","address_id":"1879","postcode":"09000","other_postcode":"null","name":"Lim Kee Kee","state_id":"79","state":"Kedah","country_id":"4","city_id":"95"},"billing_address":{"building_name":"","calling_code":"60","address":"106,Jalan Rimba Emas, Taman Bersatu","city":"Kulim","mobile":"10-2299239","address_id":"1879","postcode":"09000","other_postcode":"null","name":"Lim Kee Kee","state_id":"79","state":"Kedah","country_id":"4","city_id":"95"},"addon_services":"[{\"id\":1},{\"id\":2},{\"id\":3}]"}&session_id=Avz1WgWLFXTw3-GKm9EeP7Hj049CNaYg2Keaj30IcOCu&confirm_order=0&source=1&type=daigou&device=0&country_id=4&products=[{"id":138554}]
     */
    public void postPack(List<OrderPackServiceModel> serviceModels) {
        if (GlobalValue.isDebug && false) {
            getView().postPackResult();
            return;
        }
        if (lastMap != null && lastExtraMap != null) {
            //防止干扰
            MapHelper postMap = MapHelper.newHashMap();
            MapHelper postExtraMap = MapHelper.newHashMap();
            postMap.putAll(lastMap);
            postExtraMap.putAll(lastExtraMap);
            /*
            无参传 []
            有参传 [1,2]
             */
            postExtraMap.put("addon_services", getAddServiceIds(serviceModels));
            postMap.put("extra_data", JsonUtil.INSTANCE.anyToJson(postExtraMap) + "");
            baseSubscribe(apiService.postPack(postMap), resultModel -> {
                if (resultModel.isSuccess()) {
                    getView().postPackResult();
                }
            });
        }
    }

    /**
     * todo:获取价格详细,自营商品没有国内物流费用,静态参数,动态参数,包括国际物流方式,支付方式,等等
     * todo:1.首先获取地址,有地址则继续下一步,无地址请求默认地址传回UI继续下一步
     * todo:2.获取国际物流方式,有则下一步,无则请求传回UI再下一步
     * todo:3,获取支付方式,有则下一步,无则请求传回UI再下一步
     * todo:4,请求订单价格详细,传回UI
     *
     * @param extraMap 扩展参数
     */
    public void getPackData(MapHelper extraMap) {
        lastMap = null;
        lastExtraMap = null;
        Observable<ResultModel<OrderPackModel>> observable = Observable.just(1)
                //检测是否存在了地址
                .flatMap(new Function<Integer, ObservableSource<Integer>>() {
                    @Override
                    public ObservableSource<Integer> apply(Integer integer) throws Exception {
                        return getAddressOb(extraMap, false);
                    }
                })
                //检测是否存在了国际物流方式
                .flatMap(new Function<Integer, ObservableSource<Integer>>() {
                    @Override
                    public ObservableSource<Integer> apply(Integer integer) throws Exception {
                        if (!extraMap.containsKey("international_delivery_method")) {
                            return getInternationalDeliveryMethodsOb(extraMap);
                        }
                        return Observable.just(1);
                    }
                })
                .flatMap(new Function<Integer, ObservableSource<ResultModel<OrderPackModel>>>() {
                    @Override
                    public ObservableSource<ResultModel<OrderPackModel>> apply(Integer integer) throws Exception {
                        MapHelper map = MapHelper.newHashMap();
                        map.put("member_id", UserInfo.getMemberId());
                        map.put("language_code", LocalManageUtil.getAppLanguage() + "");
                        map.put("products", getProducts3(idList));
                        map.put("source", 1);
                        map.put("country_id", UserInfo.getCountryId());
                        map.put("session_id", PushHelper.getRegistrationId() + "");
                        map.put("extra_data", JsonUtil.INSTANCE.anyToJson(extraMap) + "");
                        map.put("confirm_order", 0);
                        map.put("type", "daigou");
                        map.put("device", "0");//0 = Android, 1 = IOS
                        lastMap = map;
                        lastExtraMap = extraMap;
                        return apiService.getPackData(map);
                    }
                });
        baseSubscribe(observable, resultModel -> {
            if (resultModel.isSuccess()) {
                getView().getPackDataResult(resultModel.getData());
            } else {
                lastMap = null;
                lastExtraMap = null;
                getView().getPackDataResult(null);
            }
        }, throwable -> {
            lastMap = null;
            lastExtraMap = null;
            getView().getPackDataResult(null);
        });
    }

    /**
     * 加入国际物流方式
     *
     * @param extraMap
     * @return
     */
    private Observable<Integer> getInternationalDeliveryMethodsOb(MapHelper extraMap) {
        return orderService.getInternationalDeliveryMethods(getDeliveryMap())
                .flatMap(new Function<ResultModel<InternationalDeliveryModel>, ObservableSource<Integer>>() {
                    @Override
                    public ObservableSource<Integer> apply(ResultModel<InternationalDeliveryModel> internationalDeliveryModelResultModel) throws Exception {
                        if (internationalDeliveryModelResultModel.isSuccess() &&
                                internationalDeliveryModelResultModel.getData() != null &&
                                internationalDeliveryModelResultModel.getData().getDeliveries() != null
                        ) {
                            List<DeliveriesBean> internationalDeliveries = new ArrayList<>();
                            for (DeliveriesBean delivery : internationalDeliveryModelResultModel.getData().getDeliveries()) {
                                if (!TextUtils.equals(delivery.getStatus(), "0")) {//状态为0的不要显示
                                    internationalDeliveries.add(delivery);
                                }
                            }
                            if (internationalDeliveries.size() > 0) {
                                extraMap.put("international_delivery_method", internationalDeliveries.get(0).getCode());
                            }
                            //todo 传回UI
                            Observable.just(internationalDeliveries)
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(s -> {
                                        getView().getInternationalDeliveryMethodResult(s);
                                    }, throwable -> {
                                        throwable.printStackTrace();
                                    });

                        }
                        return Observable.just(1);
                    }
                });
    }

    private MapHelper getDeliveryMap() {
        MapHelper map = MapHelper.newHashMap();
        map.put("session_id", PushHelper.getRegistrationId());
        map.put("member_id", UserInfo.getMemberId());
        map.put("language_code", LocalManageUtil.getAppLanguage() + "");
        map.put("source", 1);
        map.put("type", "daigou");
        map.put("country_id", UserInfo.getCountryId());
        map.put("confirm_order", 0);
        map.put("pack_order", 1);
        map.put("products", getProductsForMethod3(idList) + "");
        map.put("extra_data", getExtra_dataForDelivery(addressModel));
        return map;
    }


}